﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SalePartial.BLL.SAServiceRef;
using SalePartial.BLL;
using Telerik.Web.UI;
using System.IO;
using System.Data;

public partial class SAClientWeb_FamilyPubFrm : System.Web.UI.Page
{ 

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            PublishFrm_Load();
        }
    }

    enum PageIndex
    {
        PageOne = 1,
        PageTwo,
        PageThree
    }
    
    private List<ParameterInfo> m_curExcelParameters;
    private List<ParameterInfo> m_curKeyParameters;
    private Guid m_curFamilyId;

    private FamilyInfo m_editFamilyInfo;
    private FamilyAttrInfo m_editFamilyAttrInfo;

    //shared.
    private void PublishFrm_Load()
    {
        InitCommonData();
        InitSpecialData();

        //have to hook events here.
        //ExcelServiceMethod.RaiseStartReadEvent += new ExcelServiceMethod.StartReadEventHandler(ExcelService_RaiseStartReadEvent);
        //ExcelServiceMethod.RaiseEndReadEvent += new ExcelServiceMethod.EndReadEventHandler(ExcelService_RaiseEndReadEvent);
        //ExcelServiceMethod.RaiseStepEvent += new ExcelServiceMethod.StepEventHandler(ExcelService_RaiseStepEvent);
    }

    public void button_wizardPrevious_Click(object sender, EventArgs e)
    {
        int curIdx = this.tabControl_wizard.SelectedIndex;
        if (curIdx == 0)
        {
            return;
        }

        this.tabControl_wizard.SelectedIndex = curIdx - 1;
        this.button_wizardNext.Enabled = true;

        if (this.tabControl_wizard.SelectedIndex == 0)
        {
            this.button_wizardPrevious.Enabled = false;
        }
        else
        {
            this.button_wizardPrevious.Enabled = true;
        }

        this.button_publish.Visible = false;
    }

    public void button_wizardNext_Click(object sender, EventArgs e)
    {
        int curIdx = this.tabControl_wizard.SelectedIndex;

        //if (curIdx == 0)
        //{
        //    if (!this.CheckInputForPageOne()) return;

            this.tabControl_wizard.SelectedIndex = curIdx + 1; //the second page
            this.button_wizardPrevious.Enabled = true;
            this.button_wizardNext.Enabled = true;
            this.button_publish.Visible = false;

            //set the model path to window title.
            //this.Text = this.textBox_partPath.Text;
        //}
        //else if (curIdx == 1)
        //{
        //    if (!this.CheckInputForPageTwo()) return;

            this.tabControl_wizard.SelectedIndex = curIdx + 1; //this third page.
            this.button_wizardPrevious.Enabled = true;
            this.button_wizardNext.Enabled = true;
            this.button_publish.Visible = true;

        //    OnLoadExcel();
        //    //this.Text = "Excel path";
        //}
        //else if (curIdx == 2)
        //{
        //    return;
        //}

        //return;
    }

    //page one.
    //init methods.
    private void InitCommonData()
    {
        List<VendorInfo> vendorList = SABLL.GetAllVendors();
        foreach (VendorInfo info in vendorList)
        {
            this.comboBox_venderList.Items.Add(new RadComboBoxItem(info.Name, info.VendorId.ToString()));
        }

        List<StandardInfo> standList = SABLL.GetAllStandards();
        foreach (StandardInfo info in standList)
        {
            this.comboBox_standardList.Items.Add(new RadComboBoxItem(info.Name, info.StandardId.ToString()));
        }

        this.treeView_categoryList.Nodes.Clear();
        List<CategoryInfo> cateInfos = SABLL.GetRootCategories();

        if (cateInfos == null)
        {
            return;
        }

        for (int i = 0; i < cateInfos.Count; i++)
        {
            CategoryInfo curCateInfo = cateInfos[i];

            AddNodeByCategoryInfo(this.treeView_categoryList.Nodes, curCateInfo);
        }

        this.treeView_categoryList.ExpandAllNodes();

    }

    private static void AddNodeByCategoryInfo(RadTreeNodeCollection nodes, CategoryInfo cateInfo)
    {
        //add this node.
        RadTreeNode newNode = new RadTreeNode();
        newNode.Text = cateInfo.Name;
        newNode.Value = cateInfo.Id.ToString();
        nodes.Add(newNode);

        //add sub node.
        //get sub nodes.
        List<CategoryInfo> cateInfos = SABLL.GetSubCategories(cateInfo);

        if (cateInfos == null)
        {
            return;
        }

        foreach (CategoryInfo tempCateInfo in cateInfos)
        {
            AddNodeByCategoryInfo(newNode.Nodes, tempCateInfo);
        }
    }

    private void InitSpecialData()
    {
        this.button_wizardPrevious.Enabled = false;
        this.button_publish.Visible = false;
        if (this.comboBox_venderList.Items.Count > 0)
            this.comboBox_venderList.SelectedIndex = 0;
        if (this.comboBox_standardList.Items.Count > 0)
            this.comboBox_standardList.SelectedIndex = 0;
        m_curFamilyId = Guid.NewGuid(); //create new Guid.
        m_curExcelParameters = new List<ParameterInfo>();
        //m_curModelParameters = new Dictionary<string, ParameterInfo>();
    }

    private void button_partPathBrowser_Click(object sender, EventArgs e)
    {
        //this.textBox_partPath.Text = SABLL.OpenFileBrowser(FileType.kModel);

        // //get & set the file name.
        //this.textBox_familyName.Text = Path.GetFileName(this.textBox_partPath.Text);

    }


    private bool CheckInputForPageOne()
    {
        
        if (this.textBox_partPath.UploadedFiles.Count<1)
        {
            SABLL.ShowInfoMsg(this, @"模型文件路径不能为空！");
            return false;
        }

        //if (!File.Exists(this.textBox_partPath.Text))
        //{
        //    SABLL.ShowInfoMsg(@"模型文件不存在！");
        //    return false;
        //}
        

        if (String.IsNullOrEmpty(this.textBox_familyName.Text))
        {
            SABLL.ShowInfoMsg(this, @"模型文件名不能为空！");
            return false;
        }



        if (this.treeView_categoryList.SelectedNode == null)
        {
            SABLL.ShowInfoMsg(this, @"类别不能为空,请选择类别！");
            return false;
        }

        return true;
    }

    private bool CheckInputForPageTwo()
    {
        /*
        if (this.treeView_excelParams.Nodes.Count == 0)
        {
            SABLL.ShowInfoMsg(@"Excel参数列表不能为空！");
            return false;
        }

        if (this.dataGridView_paramsEditor.Rows.Count == 0)
        {
            SABLL.ShowInfoMsg(@"驱动参数列表不能为空！");
            return false;
        }
         */

        int cnt = this.dataGridView_paramsEditor.Rows.Count;

        for (int i = 0; i < cnt; i++)
        {
            //ParameterInfo curParam = this.dataGridView_paramsEditor.Rows[i] as ParameterInfo;
            ParameterInfo curParam = new ParameterInfo();
            if (curParam == null)
            {
                continue;
            }

            //only check drive paramters.
            if (curParam.IsDriver)
            {
                string tag = Convert.ToString(this.dataGridView_paramsEditor.Rows[i].Cells[3].Text);

                if (!SABLL.CheckTag(tag))
                {
                    SABLL.ShowInfoMsg(this, String.Format("无法识别驱动参数[{0}]的属性值[{1}], 请检查属性值规范，然后重新设置!", curParam.Name, tag));
                    return false;
                }
            }
        }

        return true;
    }

    private bool CheckInputForPageThree()
    {
        return true;
    }
    //page two.
    public void button_getTemplateParams_Click(object sender, EventArgs e)
    {
        //this.Cursor = Cursors.WaitCursor;
        try
        {
            string modelPath = this.textBox_partPath.UploadedFiles[0].FileName;

            if (!SABLL.CheckPath(modelPath)) return;

            Dictionary<string, ParameterInfo> m_curModelParameters = SABLL.GetModelParameters(modelPath);

            if (m_curModelParameters == null)
            {
                SABLL.DoAlert(this);
                return;
            }


            if (this.treeView_modelParams == null || m_curModelParameters == null)
            {
                return;
            }
            //treeView.HideSelection = false;
            this.treeView_modelParams.Nodes.Clear();

            foreach (string paramName in m_curModelParameters.Keys)
            {
                ParameterInfo paramInfo = m_curModelParameters[paramName];

                AddTreeNode(treeView_modelParams.Nodes, paramInfo);
            }

        }
        catch (System.Exception ex)
        {
            SABLL.ShowErrMsg(this, ex.Message);
        }
        finally
        {
            //this.Cursor = Cursors.Default;
        }
    }

    private static RadTreeNode AddTreeNode(RadTreeNodeCollection nodes, ParameterInfo paramInfo)
    {
        RadTreeNode newNode = new RadTreeNode();
        newNode.Text = paramInfo.Name;
        newNode.Value = paramInfo.ID.ToString();
        
        nodes.Add(newNode);

        newNode.Nodes.Add(new RadTreeNode("DisplayName:" + Convert.ToString(paramInfo.DisplayName)));
        newNode.Nodes.Add(new RadTreeNode("ID:" + Convert.ToString(paramInfo.ID)));
        newNode.Nodes.Add(new RadTreeNode("FamilyId:" + Convert.ToString(paramInfo.FamilyID)));
        newNode.Nodes.Add(new RadTreeNode("RefKey:" + paramInfo.RefKey));
        newNode.Nodes.Add(new RadTreeNode("IsDriver:" + paramInfo.IsDriver.ToString()));
        newNode.Nodes.Add(new RadTreeNode("IsKey:" + paramInfo.IsKey.ToString()));
        newNode.Nodes.Add(new RadTreeNode("IsCustom:" + paramInfo.IsCustom.ToString()));
        newNode.Nodes.Add(new RadTreeNode("Tag:" + Convert.ToString(paramInfo.Tag)));
        newNode.Nodes.Add(new RadTreeNode("Unit:" + Convert.ToString(paramInfo.Unit)));

        return newNode;
    }

    public void button_getExcelParams_Click(object sender, EventArgs e)
    {
        //check model parameters.
        //if (this.treeView_modelParams.Nodes.Count == 0)
        //{
        //    SABLL.ShowInfoMsg("模型参数列表未初始化, 请先提取模型参数！");
        //    return;
        //}

        //string excelFilePath = SABLL.OpenFileBrowser(FileType.kExcel);

        //if (String.IsNullOrEmpty(excelFilePath))
        //{
        //    return;
        //}

        ////cache file path.
        //m_curExcelPath = excelFilePath;

        //if (!SABLL.CheckPath(excelFilePath)) return;

        //try
        //{
        //    m_curExcelParameters = SABLL.GetExcelParameters(m_curModelParameters, excelFilePath);

        //    if (m_curExcelParameters == null)
        //    {
        //        SABLL.DoAlert();
        //        return;
        //    }

        //    foreach (ParameterInfo tempParam in m_curExcelParameters)
        //    {
        //        tempParam.FamilyID = new Guid(m_curFamilyId);
        //    }

        //    SABLL.InitExcelParametersTreeView(this.treeView_excelParams, m_curExcelParameters);
        //}
        //catch (System.Exception ex)
        //{
        //    SABLL.ShowErrMsg(ex.Message);
        //}
        //finally
        //{
        //}
    }

    //page three
    private void OnLoadExcel()
    {
        this.button_wizardPrevious.Enabled = false;
        this.button_publish.Enabled = false;

        try
        {
            //bool ret = SABLL.InitFamilyTableGridView(this.dataGridView_familyTable, m_curExcelPath);
            //if (!ret) SABLL.DoAlert();
        }
        catch (System.Exception ex)
        {
            SABLL.ShowErrMsg(this, ex.Message);
        }
        this.button_wizardPrevious.Enabled = true;
        this.button_publish.Enabled = true;
    }

    void ExcelService_RaiseStartReadEvent(object sender, EventArgs e)
    {
        //this.progressBar_tableLoadProgress.Step = 1;
        //this.progressBar_tableLoadProgress.Minimum = 1;
        //this.progressBar_tableLoadProgress.Maximum = 100;
        //this.progressBar_tableLoadProgress.Value = 1;

        //Application.DoEvents();
    }

    void ExcelService_RaiseStepEvent(object sender, EventArgs e)
    {
        //this.progressBar_tableLoadProgress.PerformStep();
        //Application.DoEvents();
    }

    void ExcelService_RaiseEndReadEvent(object sender, EventArgs e)
    {
        //this.progressBar_tableLoadProgress.Value = 100;
        //Application.DoEvents();
    }


    public void button_publish_Click(object sender, EventArgs e)
    {
        //this.Cursor = Cursors.WaitCursor;
        this.button_publish.Enabled = false;
        bool success = DoPublish();
        this.button_publish.Enabled = true;
        //this.Cursor = Cursors.Default;

        if (success == true)
        {
            //this.Close();
        }
    }

    private bool DoPublish()
    {
        FamilyInfo familyInfo = CollectFamilyInfo();
        FamilyAttrInfo familyAttrInfo = CollectFamilyAttrInfo();
        FamilyTableInfo familyTableInfo = CollectFamilyTableInfo();

        bool success = SABLL.UpdateFamily(familyInfo, familyAttrInfo, familyTableInfo);

        if (success)
        {
            SABLL.ShowInfoMsg(this, "发布成功！");
        }
        else
        {
            SABLL.ShowErrMsg(this, "发布失败！" + SABLL.GetLastErrMsg());
        }

        return success;
    }

    private FamilyInfo CollectFamilyInfo()
    {
        FamilyInfo familyInfo = m_editFamilyInfo;
        //familyInfo.ID = m_curFamilyId;
        familyInfo.Name = this.textBox_familyName.Text;
        familyInfo.IsCached = false;

        //standard id
        string curStandardValue = this.comboBox_standardList.SelectedValue;
        if (curStandardValue != null)
        {
            familyInfo.StandardID = int.Parse(curStandardValue);
        }
        else
            familyInfo.StandardID = -1;

        //vendor id
        string curVendorValue = this.comboBox_venderList.SelectedValue;
        if (curVendorValue != null)
        {
            familyInfo.VendorID = int.Parse(curVendorValue);
        }
        else
            familyInfo.VendorID = -1;

        //get selected category.
        //
        RadTreeNode selectedNode = this.treeView_categoryList.SelectedNode;
        string curCategoryInfo = selectedNode.Value;

        familyInfo.CategoryID = new Guid(curCategoryInfo);
        familyInfo.DisplayName = this.textBox_familyName.Text;

        return familyInfo;
    }

    private FamilyTableInfo CollectFamilyTableInfo()
    {
        FamilyTableInfo retInfo = new FamilyTableInfo();
        retInfo.FamilyID = m_curFamilyId;

        //need to compute parameter edit datagridview.
        //
        int keyParamCnt = this.dataGridView_paramsEditor.Rows.Count;
        for (int i = 0; i < keyParamCnt; i++)
        {
            //DataGridViewRow curRow = this.dataGridView_paramsEditor.Rows[i];
            //if (curRow.Tag == null) continue;
            //ParameterInfo curKeyParamInfo = curRow.Tag as ParameterInfo;
            //if (curKeyParamInfo == null) continue;

            //curKeyParamInfo.IsKey = true;
            //curKeyParamInfo.Idx = i+1;
            //curKeyParamInfo.DisplayName = Convert.ToString(curRow.Cells[1].Value);

            //if (curKeyParamInfo.IsDriver)
            //{
            //    curKeyParamInfo.IsCustom = Convert.ToBoolean(curRow.Cells[2].Value);
            //    if (curKeyParamInfo.IsCustom)
            //    {
            //        curKeyParamInfo.Tag = Convert.ToString(curRow.Cells[3].Value);
            //    }
            //}
        }

        retInfo.Parameters = m_curExcelParameters.ToArray();

        DataTable retTable = new DataTable();
        retTable.TableName = "FamilyTable";
        int columnCnt = this.dataGridView_familyTable.Columns.Count;
        int rowCnt = this.dataGridView_familyTable.Rows.Count;

        //add columns.
        for (int c = 0; c < columnCnt; c++)
        {
            string title = Convert.ToString(this.dataGridView_familyTable.Columns[c].HeaderText);

            retTable.Columns.Add(title, System.Type.GetType("System.String"));
        }

        //add rows.
        for (int r = 0; r < rowCnt; r++)
        {
            DataRow newRow = retTable.NewRow();

            //if all values are empty, don't save it.
            bool allEmtpy = true;
            for (int j = 0; j < columnCnt; j++)
            {
                string cellVal = Convert.ToString(this.dataGridView_familyTable.Rows[r].Cells[j].Text);
                if (allEmtpy && !String.IsNullOrEmpty(cellVal))
                {
                    allEmtpy = false;
                }
                newRow[j] = cellVal;
            }
            if (!allEmtpy)
            {
                retTable.Rows.Add(newRow);
            }
        }

        retInfo.FamilyTable = retTable;
        //
        // retInfo.Parameters
        return retInfo;
    }

    private FamilyAttrInfo CollectFamilyAttrInfo()
    {
        FamilyAttrInfo retInfo = new FamilyAttrInfo();
        retInfo.FamilyID = m_curFamilyId;
        retInfo.Vendor = this.comboBox_venderList.Text;
        retInfo.Description = this.richTextBox_familyDescription.Text;

        //string templateFileName = this.textBox_partPath.Text.Trim();
        string drawingName = this.textBox_familyDwg.UploadedFiles[0].FileName.Trim();
        string drawPicName = this.textBox_familyDwgPic.UploadedFiles[0].FileName.Trim();
        string modelPicName = this.textBox_familyPic.UploadedFiles[0].FileName.Trim();
        string referenceName = this.textBox_familyTechDoc.UploadedFiles[0].FileName.Trim();

        //get the binaries.
        //
        //retInfo.TemplateFileName = Path.GetFileName(templateFileName);
        //retInfo.TemplateFileBinary = SABLL.GetBinaryByPath(templateFileName);

        retInfo.DrawingName = Path.GetFileName(drawingName);
        retInfo.DrawingBinary = SABLL.GetBinaryByPath(drawingName);

        retInfo.DrawPicName = Path.GetFileName(drawPicName);
        retInfo.DrawPicBinary = SABLL.GetBinaryByPath(drawPicName);

        retInfo.ModelPicName = Path.GetFileName(modelPicName);
        retInfo.ModelPicBinary = SABLL.GetBinaryByPath(modelPicName);

        retInfo.ReferenceName = Path.GetFileName(referenceName);
        retInfo.ReferenceBinary = SABLL.GetBinaryByPath(referenceName);

        return retInfo;
    }

    private ParameterInfo GetSelectedNodeParameterInfo()
    {
        RadTreeNode curNode = this.treeView_excelParams.SelectedNode;
        if (curNode == null)
        {
            SABLL.ShowInfoMsg(this, @"请先选择可用参数！");
            return null;
        }

        if (curNode.Value == null) //this is sub node.
            curNode = curNode.ParentNode;

        if (curNode == null)
        {
            SABLL.ShowInfoMsg(this, @"所选节点无效，请重新选择！");
            return null;
        }

        string value = curNode.Value;
        if (value == null)
        {
            SABLL.ShowErrMsg(this, @"所选节点参数数据丢失, 请重新选择！");
            return null;
        }
        //search 
        ParameterInfo curParam = new ParameterInfo();

        if (curParam.IsKey)
        {
            SABLL.ShowErrMsg(this, String.Format("参数[{0}]已经设置为关键参数, 不能重复添加！", curParam.Name));
            return null;
        }

        return curParam;
    }

    private void AddParameterInfoIntoEditGridView(ParameterInfo curParam)
    {
        //    this.dataGridView_paramsEditor.AllowUserToAddRows = true;
        //    int newRowIndex = this.dataGridView_paramsEditor.Rows.Add();
        //    this.dataGridView_paramsEditor.AllowUserToAddRows = false;

        //    DataGridViewRow newRow = this.dataGridView_paramsEditor.Rows[newRowIndex];
        //    newRow.Tag = curParam;
        //    newRow.Cells[0].Value = curParam.Name;
        //    newRow.Cells[1].Value = curParam.DisplayName;
        //    DataGridViewCheckBoxCell curCheckBoxCell = (DataGridViewCheckBoxCell)newRow.Cells[2];

        //    if (!curParam.IsDriver)
        //    {
        //        curCheckBoxCell.Value = false;
        //        curCheckBoxCell.ReadOnly = true;
        //        curCheckBoxCell.Style.BackColor = Color.LightGray;
        //        newRow.Cells[3].ReadOnly = true;
        //        newRow.Cells[3].Style.BackColor = curCheckBoxCell.Style.BackColor;
        //    }
        //    else
        //    {
        //        newRow.Cells[0].Style.ForeColor = Color.Red;
        //        curCheckBoxCell.Value = curParam.IsCustom;
        //        curCheckBoxCell.ReadOnly = false;
        //        newRow.Cells[3].ReadOnly = false;
        //    }
        //    this.dataGridView_paramsEditor.ClearSelection();
        //    newRow.Selected = true;

        //    //set the parameter key to true when added.
        //    curParam.IsKey = true;
    }

    public void button_selectParam_Click(object sender, EventArgs e)
    {
        ParameterInfo curParam = GetSelectedNodeParameterInfo();

        if (curParam == null)
        {
            return;
        }

        AddParameterInfoIntoEditGridView(curParam);
    }

    //private void button_deleteKeyParam_Click(object sender, EventArgs e)
    //{
    //    DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);

    //    if (selectedRow != null)
    //    {
    //        ParameterInfo curKeyParam = selectedRow.Tag as ParameterInfo;

    //        this.dataGridView_paramsEditor.Rows.Remove(selectedRow);

    //        if (curKeyParam != null)
    //        {
    //            //set the parameter key to false when removed.
    //            curKeyParam.IsKey = false;
    //            curKeyParam.Idx = 0;
    //        }
    //    }
    //}

    //private void button_moveUp_Click(object sender, EventArgs e)
    //{
    //    DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);
    //    if (selectedRow != null && selectedRow.Index > 0)
    //    {
    //        int pos = selectedRow.Index - 1;
    //        this.dataGridView_paramsEditor.Rows.Remove(selectedRow);
    //        this.dataGridView_paramsEditor.Rows.Insert(pos, selectedRow);
    //        this.dataGridView_paramsEditor.ClearSelection();
    //        selectedRow.Selected = true;
    //    }
    //}

    //private void button_moveDown_Click(object sender, EventArgs e)
    //{
    //    DataGridViewRow selectedRow = SABLL.GetSelectedRow(this.dataGridView_paramsEditor);
    //    if (selectedRow != null && selectedRow.Index < this.dataGridView_paramsEditor.Rows.Count - 1)
    //    {
    //        int pos = selectedRow.Index + 1;
    //        this.dataGridView_paramsEditor.Rows.Remove(selectedRow);
    //        this.dataGridView_paramsEditor.Rows.Insert(pos, selectedRow);
    //        this.dataGridView_paramsEditor.ClearSelection();
    //        selectedRow.Selected = true;
    //    }
    //}






}